﻿using Common.plate.common;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.plate.plateRecognizer
{
    public class Image
    {
        public static Mat ProcessImage(string imagePath, string outputPath)
        {
            string imagePatht = null;
            var imageFiles = Directory.GetFiles(imagePath, "*.jpg");
            string? outputDir = null;

            foreach (var imageFile in imageFiles)
            {
                imagePatht = imageFile;
                outputDir = Path.Combine(outputPath, Path.GetFileName(imageFile));
            }
            // 1. 读取图像
            var img = Cv2.ImRead(imagePatht);

            if (img.Empty())
            {
                Console.WriteLine($"无法加载图像: {imagePath}");
                return null;
            }
            // 初始化车牌识别器
            var plateRec = new PlateRecognizer();
            // 识别车牌
            var plateObjs = plateRec.RecognizePlate(img);
            // 更新全局车牌变量（仅保留高置信度结果）
            GlobalData.Plate = plateObjs.Any(p => p.ScoreText > 0.8f)
                ? plateObjs.First(p => p.ScoreText > 0.8f).Text
                : null;
            // 绘制识别结果（边界框和文字）
            ResultVisualizer resultVisualizer = new ResultVisualizer();
            foreach (var obj in plateObjs.Where(p => p.ScoreText > 0.8f))
            {
                resultVisualizer.DrawDetectionWithChinese1(img, obj);
            }
            //Cv2.ImShow("车牌识别", img);
            //Cv2.WaitKey(1000);
            //Console.WriteLine($"车牌号：{GlobalData.Plate}");

            if (!string.IsNullOrEmpty(outputDir))
            {
                Cv2.ImWrite(outputDir, img);
                Console.WriteLine($"处理完成，结果已保存到 {outputPath}");
            }
            return img;

        }
    }
}
